<?php

namespace App\Module\Admin\Controllers;

use App\Observers\BaseSettingObserver;
use App\System\Base\Model\BaseSetting;
use App\System\Base\Services\SmsService;
use App\System\Cis\Model\CisUser;
use App\System\Cis\Services\DailyWagePlanningTaskService;
use App\System\Cis\Services\DeclarationInputValidationService;
use App\System\Cis\Services\DeclarationStorageService;
use App\System\Log\Repositories\LogDeclarationFormRepository;
use App\System\Fina\Repositories\FinaIntegralRegRecordRepository;
use Illuminate\Http\Request;
use App\System\Cis\Repositories\CisUserRepository;
use Excel;

/**
 * Class MemberController 会员管理
 * @package App\Module\Admin\Controllers
 */
class MemberController extends Controller
{
    /**
     * 创客管理页面
     */
    public function index(Request $request)
    {
        $keyword = $request['keyword']??'';
        $page = $request['page']??1;
        $type = $request['type']??1;
        $where = ['keyword'=>$keyword,'page'=>$page,'type'=>$type];
        $user = CisUserRepository::getInstance();
        $data = $user->getList($keyword,$type);
        return view('admin.member.index',compact('data','where'));
    }

    //修改创客帐号
    public function changeUserStatus(Request $request)
    {
        if ($request->isMethod('post')) {
            $thepost = $request->only('id','status', 'user_type','user_renew');
            $id = $thepost['id'];
            $updata['status'] = $thepost['status']??0;//改变用户状态
            $updata['user_type'] = $thepost['user_type']??0;//设为城市合伙人
            $updata['user_renew'] = $thepost['user_renew']??0;//复消
            $user = CisUserRepository::getInstance();
            $res = $user->updateData($id, $updata);
            $msg = $res['message'] ?? '操作失败';
            $state = !empty($res['data']) ? 'SUCCESS' : 'FAIL';
            return response()->json(['message' => $msg, 'status' => $state, 'url' => '']);
        }
    }

    /**
     * 会员资金页面
     */
    public function cash(Request $request)
    {
        $user_id = $request['id'];
        $type = $request['type']??0;
        $where = ['type'=>$type,'id'=>$user_id];
        $finance = FinaIntegralRegRecordRepository::getInstance();
        $data = $finance->getList($type,'','','','',11,'',false,$user_id);
        return view('admin.member.cash',compact('data','where'));
    }

    /**
     * 修改会员资金页面
     */
    public function editCash(Request $request)
    {
        $user_id = $request['id'];
        $user = CisUserRepository::getInstance();
        $userInfo = $user->getUser($user_id);
        return view('admin.member.editCash',compact('userInfo'));
    }

    public function ajaxSaveEditCash(Request $request)
    {
        if($request->isMethod('post')){
            $thepost = $request->only('user_id','integral_type','integral_number','coin_type','coin_number','reasons');
            $data['user_id'] = $thepost['user_id']??0;
            $data['integral_type'] = $thepost['integral_type']??0;
            $data['integral_number'] = $thepost['integral_number']??0;
            $data['coin_type'] = $thepost['coin_type']??0;
            $data['coin_number'] = $thepost['coin_number']??0;
            $data['reasons'] = $thepost['reasons']??'';
            if(!$data['integral_number'] && !$data['coin_number']){
                return response()->json(['message' => '未填入变动数量！', 'status' => 'FAIL', 'url' => '']);
            }
            $fiance = FinaIntegralRegRecordRepository::getInstance();
            $res = $fiance->fundAdjustment($data);
            $msg = $res['message'] ?? '操作失败';
            $state = !empty($res['data']) ? 'SUCCESS' : 'FAIL';
            $url = !empty($res['data']) ? url('/admin/member/cash/'.$data['user_id']) : '';
            return response()->json(['message' => $msg, 'status' => $state, 'url' => $url]);
        }
    }

    /**
     * 会员管理详情页面
     */
    public function view(Request $request)
    {
        $id = $request['id'];
        $user = CisUserRepository::getInstance();
        $data = $user->getUser($id);
        $referInfo = $user->getUser($data->referee_id);
        return view('admin.member.view',compact('data','referInfo'));
    }

    /**
     * 会员管理导出用户
     */
    public function export(Request $request)
    {
        $keyword = $request['keyword'];
        $type = $request['type'];
        $user = CisUserRepository::getInstance();
        $ret = $user->getList($keyword,$type,true);
        $arr[] = array('ID', '创客昵称', '手机号码', '创客类别', '总业绩', '创业区业绩', '创新区业绩', '创客区业绩', '积分', '注册币', '注册时间', '复消日期', '推荐数');
        foreach ($ret as $v) {
            $thearr = array();
            $thearr[] = $v->id;
            $thearr[] = $v->name;
            $thearr[] = $v->mobile;
            $thearr[] = $v->user_type==1?'创客':'城市合伙人';
            $thearr[] = $v->entrepreneurship_achievement+$v->chuangheng_achievement+$v->director_achievement;
            $thearr[] = $v->entrepreneurship_achievement;
            $thearr[] = $v->chuangheng_achievement;
            $thearr[] = $v->director_achievement;
            $thearr[] = $v->integral;
            $thearr[] = $v->registered_currency;
            $thearr[] = $v->created_at;
            $thearr[] = $v->repeated_consumption_date;
            $thearr[] = $v->recommend_number;
            $arr[] = $thearr;
        }

        Excel::create(iconv('UTF-8', 'GBK', '创客列表'), function ($excel) use ($arr) {
            $excel->sheet('创客列表', function ($sheet) use ($arr) {
                $sheet->rows($arr);
            });
        })->export('xls');
    }

    // 创客转账页面
    public function transferCoin(Request $request){
        $id = $request['id'];
        $user = CisUserRepository::getInstance();
        $userInfo = $user->getUser($id);
        if($request->isMethod('post')){
            $thepost = $request->only('user_id','coin_number','receiver','reasons');
            if($thepost['coin_number'] > $userInfo->registered_currency){
                return response()->json(['message'=> '超过额度！', 'status' => 'FAIL']);
            }
            if($thepost['user_id'] == $thepost['receiver']){
                return response()->json(['message'=> '不能转给本帐号！', 'status' => 'FAIL']);
            }
            if(!CisUser::find($thepost['receiver'])){
                return response()->json(['message'=> '接收用户不存在！', 'status' => 'FAIL']);
            }
            $cisUser = CisUserRepository::getInstance();
            $res = $cisUser->transferCoin($thepost);
            $msg = $res['message'] ?? '操作失败';
            $state = !empty($res['data']) ? 'SUCCESS' : 'FAIL';
            $url = !empty($res['data']) ? route('admin.member.index') : '';
            return response()->json(['message' => $msg, 'status' => $state, 'url' => $url]);
        }
        return view('admin.member.transferCoin',compact('userInfo'));
    }

    //创客报单
    public function memberList(Request $request)
    {
        $keyword = $request['keyword']??'';
        $page = $request['page']??1;
        $where = ['keyword'=>$keyword,'page'=>$page];
        $log = LogDeclarationFormRepository::getInstance();
        $data = $log->getList($keyword);
        return view('admin.member.memberList',compact('data','where'));
    }

    // 新增报单
    public function addMember(Request $request)
    {
        if($request->isMethod('post'))
        {
            $post = $request->input();
            $input = new DeclarationInputValidationService();
            $input->generatingNumber = $post['generatingNumber'] ;
            $input->cityPartnerId = $post['cityPartnerId'];
            $input->recommendId = $post['recommendId'];
            $input->market =$post['market'];
            $input->accountOwnerMobile = $post['accountOwnerMobile'];
            $input->userInformationVerification();
            if(!$input->getErrorMsg())
            {
                $res = new DeclarationStorageService($input);
                $res->getDeclarationResult();
                if($res->getErrorMsg())
                {
                    return response()->json(['message' => $res->getErrorMsg(), 'status' =>'FAIL']);
                }
                return response()->json(['message' => '操作成功', 'status' => 'SUCCESS','url'=>url('admin/member/memberList')]);
            }
            else
            {
                return response()->json(['message' => $input->getErrorMsg(), 'status' => 'FAIL']);
            }

        }

        return view('admin.member.addMember');
    }

    //查看报单详情
    public function viewMember(Request $request)
    {
        $id = $request['id']??0;
        $log = LogDeclarationFormRepository::getInstance();
        $data = $log->getLog($id);
        if($data)
        {
            $user_id_array = [$data->user_id,$data->recommender_id];
            $user = CisUserRepository::getInstance();
            $list = $user->getByInUser($user_id_array);
            $user_list = [];
            foreach ($list as $v)
            {
                $user_list[$v->id] = $v->name ? $v->name : $v->mobile ;
            }
        }
        return view('admin.member.viewMember',compact('data','user_list'));
    }

    //工资设置
    public function setWages(Request $request)
    {
        if($request->isMethod('post'))
        {
            $post = $request->input();
            foreach ($post as $k=>$v)
            {
                if(is_numeric($k))
                {
                    BaseSetting::where('id',$k)->update(['value'=>$v]);
                }

            }
            return response()->json(['message' => '操作成功', 'status' => 'SUCCESS','url'=>url('admin/member/setWages')]);

        }
        $data = BaseSetting::get();
        $data_array = [];
        foreach ($data as $v)
        {
            $data_array[$v->id] = $v->value;
        }
        return view('admin.member.setWages',compact('data_array'));
    }

    //推荐关系图
    public function recommend(Request $request)
    {
        $id = $request['id'];
        $user = CisUserRepository::getInstance();
        $info = $user->getUser($id);
        $list = $user->getRecommendList($id);
        $where = ['id'=>$id];
        return view('admin.member.recommend',compact('info','list','where'));
    }

    //接点关系图
    public function contact(Request $request)
    {
        $user_id = $request['keyword']??'';
        $user = CisUserRepository::getInstance();
        $data = $user->getContection($user_id);
        return view('admin.member.contact',compact('data','user_id'));
    }

    public function ajaxGetContact(Request $request)
    {
        if($request->isMethod('post')){
            $thepost = $request->only('id');
            $user = CisUserRepository::getInstance();
            $data = $user->getContection($thepost['id']);
            return response()->json($data);
        }
    }

    /**
     * 临时方法，执行生成发工资记录[danny]
     */
    public function generationRecord()
    {
        //$user = CisUserRepository::getInstance();
        //$user->deleteUser();清除测试环境帐号
        if(config("app.env") == 'product')
        {
            echo 11;
            return;
        }
        $a = new DailyWagePlanningTaskService();
        $r = $a->dailyWage();
        var_dump($r);
        die;
    }

    /**
     * 临时方法，执行发放工资
     */
    public function payWages()
    {
        if(config("app.env") == 'product')
        {
            echo 11;
            return;
        }
        $a = new DailyWagePlanningTaskService();
        $r = $a->settlementDayWages();
        var_dump($r);
        die;
    }
}
